//
//  MainViewController.m
//  iOS07-Weibo-LPK-OC
//
//  Created by 罗培克 on 6/28/15.
//  Copyright © 2015 lpk. All rights reserved.
//

#import "MainViewController.h"
#import "DiscoverTableViewController.h"
#import "HomeTableViewController.h"
#import "MessageTableViewController.h"
#import "NewfeatureTableViewController.h"
#import "ProfileTableViewController.h"
#import "MainTabBar.h"

@interface MainViewController ()

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addChildViewControllers];
    
    // 使用 KVC 修改 tabBar
    [self setValue:[[MainTabBar alloc]init] forKey:@"tabBar"];
}

/// 添加所有子控制器
- (void)addChildViewControllers {
    // 从 JSON 文件读取配置信息
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Controllers.JSON" ofType:nil];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    // 反序列化为数组
    NSError *error = nil;
    NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    if (error == nil) {
        for (NSDictionary *dict in array) {
            // 添加子控制器
            [self addChildViewControllerWithVCName:dict[@"vcName"] image:dict[@"image"] selectedImage:dict[@"selectedImage"] title:dict[@"title"]];
        }
    } else {
        NSLog(@"%@", error);
    }
    
}

/// 添加一个子控制器
- (void)addChildViewControllerWithVCName:(NSString *)vcName image:(NSString *)image selectedImage:(NSString *)selectedImage title:(NSString *)title {
    
    UITableViewController *vc = [[NSClassFromString(vcName) alloc]init];
    
    vc.title = title;
    
    vc.tabBarItem = [[UITabBarItem alloc]initWithTitle:title image:[UIImage imageNamed:image] selectedImage:[UIImage imageNamed:selectedImage]];
    
    UINavigationController *nav = [[UINavigationController alloc]init];
    [nav addChildViewController:vc];
    
    [self addChildViewController:nav];
}

@end
